<?php
/**
 * Created by PhpStorm.
 * User: 郑好
 * Date: 2019/3/6
 * Time: 上午10:23
 */

namespace app\common;

use Exception;
use Predis\Client;
use Log;
use think\console\command\Lists;

class Redis
{
    use InstanceTrait;

    public static function conn()
    {
        $parameters = [
            'host' => config('redis.host'),
            'port' => config('redis.port'),
        ];

        if (!empty(config('redis.password'))) {
            $parameters['password'] = config('redis.password');
        }

        return new Client($parameters);
    }

    public function fommatDsn($redisDb = 0)
    {
        $dsn = "redis://";
        if (config('redis.user')) {
            $dsn .= config('redis.user');
        } else {
            $dsn .= "root";
        }

        if (config('redis.password')) {
            $dsn .= ":" . config('redis.password') . "@";
        } else {
            $dsn .= "@";
        }

        if (config('redis.host')) {
            $dsn .= config('redis.host');
        } else {
            $dsn .= "127.0.0.1";
        }

        if (config('redis.port')) {
            $dsn .= ":" . config('redis.port');
        } else {
            $dsn .= ":6379";
        }

        if ($redisDb > 0 && $redisDb < 16) {
            $dsn .= "/" . (int)$redisDb;
        }

        return $dsn;
    }

    public function redisGet($key)
    {
        $value = redis()->get($key);
        if (empty($value)) {
            return ["code" => _MSG_NOT_FOUND, "msg" => "未找到数据", "data" => ""];
        }
        return ["code" => _MSG_SYSTEM_SUCCESS, "msg" => "查询成功", "data" => unserialize($value)];
    }

    public function redisGetV2($key)
    {
        return redis()->get($key);
    }

    public function redisSet($key, $value, $ttl = 60 * 60 * 24 * 15)
    {
        if (!redis()->setex($key, $ttl, serialize($value))) {
            \Log::error("" . __FUNCTION__ . ": 存入redis失败 key=" . $key . " value=" . $value, []);
            return ["code" => _MSG_SYSTEM_ERROR, "msg" => "redis插入失败"];
        }
        return ["code" => _MSG_SYSTEM_SUCCESS, "msg" => "redis插入成功"];
    }

    public function redisDel($key)
    {
        redis()->del($key);
    }

    public function redisMdel($keys)
    {
        redis()->del($keys);
    }

    public function redisHSet($name, $key, $value)
    {
        if (!redis()->hset($name, $key, serialize($value))) {
            \Log::error("" . __FUNCTION__ . ": 存入redis失败 key=" . $key . " value=" . $value);
            return ["code" => _MSG_SYSTEM_ERROR, "msg" => "redis插入失败"];
        }
        return ["code" => _MSG_SYSTEM_SUCCESS, "msg" => "redis插入成功"];
    }

    public function redisHMSet($name, $data)
    {
        if (!redis()->hmset($name, $data)) {
            \Log::error("" . __FUNCTION__ . ": 存入redis失败 key=" . $name . " value=" . serialize($data));
            return ["code" => _MSG_SYSTEM_ERROR, "msg" => "redis插入失败"];
        }
        //        redis()->expire($name, 60 * 60 * 24 * 15);
        return ["code" => _MSG_SYSTEM_SUCCESS, "msg" => "redis插入成功"];
    }

    //命令用于设置 key 的过期时间，key 过期后将不再可用。单位以秒计。
    public function redisExpire($redisKey, $ttl)
    {
        redis()->expire($redisKey, $ttl);
    }

    //命令用于设置 key 的过期时间，key 过期后将不再可用。单位以毫计。
    public function redisPExpire($redisKey, $ttl)
    {
        redis()->pexpire($redisKey, $ttl);
    }

    public function redisHMSetInit($name, $data)
    {
        $op = redis()->transaction(
            function ($tx) use ($name, $data) {
                $tx->del($name);
                $tx->hmset($name, $data); // 倒序插入
                $tx->expire($name, 86400 * 15);
            }
        );
        if (!$op) {
            \Log::error("" . __FUNCTION__ . ": 存入redis失败 key=" . $name . " value=" . serialize($data));
            return ["code" => _MSG_SYSTEM_ERROR, "msg" => "redis插入失败"];
        }
        return ["code" => _MSG_SYSTEM_SUCCESS, "msg" => "redis插入成功"];
    }

    public function redisHSetTrue($name, $key)
    {
        if (!redis()->hset($name, $key, 1)) {
            // \Log::warning(__FUNCTION__.": 存入redis失败 ".$name."[".$key."=1] ", []);
            return ["code" => _MSG_SYSTEM_ERROR, "msg" => "redis插入失败"];
        }
        //        redis()->expire($name, 86400 * 15);
        return ["code" => _MSG_SYSTEM_SUCCESS, "msg" => "redis插入成功"];
    }

    public function redisHSetFalse($name, $key)
    {
        if (!redis()->hset($name, $key, 0)) {
            // \Log::warning(__FUNCTION__.": 存入redis失败 ".$name."[".$key."=0] ", []);
            return ["code" => _MSG_SYSTEM_ERROR, "msg" => "redis插入失败"];
        }
        return ["code" => _MSG_SYSTEM_SUCCESS, "msg" => "redis插入成功"];
    }

    public function redisHGetAll($name)
    {
        $value = redis()->hgetall($name);
        if (empty($value)) {
            return ["code" => _MSG_SYSTEM_ERROR, "msg" => "获取失败", "data" => []];
        }
        return ["code" => _MSG_SYSTEM_SUCCESS, "msg" => "获取成功", "data" => $value];
    }

    public function redisZadd($key, $score, $value)
    {
        redis()->zadd($key, $score, $value);
    }

    public function redisZrem($key, $list)
    {
        redis()->zrem($key, $list);
    }

    // array  zrange($key, $start, $stop, array $options = null)
    // array  zrevrange($key, $start, $stop, array $options = null)

    public function redisZRevRange($key, $start, $stop, $options = [])
    {
        $value = redis()->zrevrange($key, $start, $stop, $options);
        if (empty($value)) {
            return ["code" => _MSG_NOT_FOUND, "msg" => "未找到数据", "data" => []];
        }
        return ["code" => _MSG_SYSTEM_SUCCESS, "msg" => "查询成功", "data" => $value];
    }

    public function redisZrange($key, $start, $stop, $options = [])
    {
        $value = redis()->zrange($key, $start, $stop, $options);
        if (empty($value)) {
            return ["code" => _MSG_NOT_FOUND, "msg" => "未找到数据", "data" => []];
        }
        return ["code" => _MSG_SYSTEM_SUCCESS, "msg" => "查询成功", "data" => $value];
    }

    //根据分数默认从高到低排序
    public function redisZrangeByscore($key, $max, $min, $options = [])
    {
        $value = redis()->zrevrangebyscore($key, $max, $min, $options);
        if (empty($value)) {
            return ["code" => _MSG_NOT_FOUND, "msg" => "未找到数据", "data" => []];
        }
        return ["code" => _MSG_SYSTEM_SUCCESS, "msg" => "查询成功", "data" => $value];
    }


    public function redisZrank($key, $member)
    {
        return (int)redis()->zrank($key, $member);
    }


    /**
     * @param       $key
     * @param       $value
     * @description 初始化 redis list
     */
    public function redisSetList($key, $value)
    {
        krsort($value);
        redis()->transaction(
            function ($tx) use ($key, $value) {
                $tx->del($key);
                $tx->lpush($key, $value); // 倒序插入
            }
        );
    }

    /**
     * @param       $key
     * @param       $value
     * @description 左推 redis list
     */
    public function redisLpush($key, $value)
    {
        try {
            redis()->transaction(
                function ($tx) use ($key, $value) {
                    $tx->lpush($key, serialize($value));
                    $tx->rPop($key);
                }
            );
        } catch (Exception $e) {
            \Log::error("" . __FUNCTION__ . "存入redis失败" . $e->getMessage(), []);
        }
    }

    public function redisLlen($key)
    {
        if (!redis()->exists($key)) {
            return 0;
        }
        return redis()->llen($key);
    }

    public function redisGetList($key)
    {
        try {
            $list = redis()->lrange($key, 0, -1);
            foreach ($list as $key => $value) {
                $list[$key] = unserialize($value);
            }
            return ["code" => _MSG_SYSTEM_SUCCESS, "msg" => "查询成功", "data" => ["list" => $list]];
        } catch (Exception $e) {
            \Log::error("" . __FUNCTION__ . "获取redis list失败" . $e->getMessage(), []);
            return ["code" => _MSG_NOT_FOUND, "msg" => "未找到数据", "data" => []];
        }
    }

    public function redisLrange($key, $start, $stop)
    {
        try {
            $list = redis()->lrange($key, $start, $stop);
            foreach ($list as $key => $value) {
                $list[$key] = unserialize($value);
            }

            return ["code" => _MSG_SYSTEM_SUCCESS, "msg" => "查询成功", "data" => ["list" => $list]];
        } catch (Exception $e) {
            \Log::error("" . __FUNCTION__ . "获取redis list失败" . $e->getMessage(), []);
            return ["code" => _MSG_NOT_FOUND, "msg" => "未找到数据", "data" => []];
        }
    }

    public function redisMget($list)
    {
        $list = redis()->mget($list);
        foreach ($list as $k => $v) {
            $list[$k] = unserialize($v);
        }
        return $list;
    }

    public function redisIncre($key)
    {
        return redis()->incr($key);
    }

    public function redisHincre($name, $key, $increNum = 1)
    {
        return redis()->hincrby($name, $key, $increNum);
    }

    public function redisHMgetNum($key, $list)
    {
        $list = redis()->hmget($key, $list);
        foreach ($list as $k => $v) {
            $list[$k] = (int)$v;
        }
        return $list;
    }

    public function redisHMget($key, $list)
    {
        $list = redis()->hmget($key, $list);
        return $list;
    }

    public function redisSadd($key, $list)
    {
        redis()->sadd($key, $list);
    }

    public function redisSrem($key, $list)
    {
        redis()->srem($key, $list);
    }

    public function redisScount($key)
    {
        redis()->scard($key);
    }

    public function redisZcard($key)
    {
        return redis()->zcard($key);
    }

    public function redisHautoSet($name, $key, $v)
    {
        try {
            if (redis()->hexists($name, $key)) {
                //redis()->hdel($name, $key);
                $status = 2;
            } else {
                redis()->hset($name, $key, $v);
                $status = 1;
            }
            return $status;
        } catch (Exception $e) {
            return 0;
        }
    }

    public function redisHexists($name, $key)
    {
        return redis()->hexists($name, $key);
    }

    public function redisHlen($key)
    {
        return redis()->hlen($key);
    }

    public function redisHgetKeysAsKey($key)
    {
        $list = redis()->hkeys($key);
        $kv = [];
        if (!empty($list)) {
            foreach ($list as $value) {
                $kv[$value] = 1;
            }
        }
        return $kv;
    }

    public function redisHgetKeys($key)
    {
        $list = redis()->hkeys($key);
        return $list;
    }

    public function redisHdel($name, $keys)
    {
        return redis()->hdel($name, $keys);
    }

    public function redisHget($name, $key)
    {
        return redis()->hget($name, $key);
    }

    /*
     * 有序集合自增长
     */
    public function redisZincrby($key, $increment, $member)
    {
        return redis()->zincrby($key, $increment, $member);
    }

    /*
     * 获取有序集合的分数
     */
    public function redisZscore($key, $member)
    {
        $value = redis()->zscore($key, $member);
        return intval($value);
    }

    /*
     * 如果不存在设置键值，如果存在返回0
     */
    public function redisSetNx($key, $value)
    {
        return redis()->setnx($key, $value);
    }

    /*
     * redis 锁
     */
    public function redisSetNxTime($key, $value, $time)
    {
        return redis()->set($key, $value, 'ex', $time, 'nx');
    }

    /*
     * redis 队列右进
     */
    public function redisRPush($key, $value)
    {
        return redis()->rpush($key, $value);
    }

    /*
     * redis 队列左出
     */
    public function redisLPop($key)
    {
        return redis()->lpop($key);
    }

    /*
     * 判断一个是否是否在一个无序集合内
     * return bool
     */
    public function redisSismember($key, $value)
    {
        $res = redis()->sismember($key, $value);
        if ($res) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 返回有序集合分数内的总数
     */
    public function redisZcount($key, $min, $max)
    {
        return redis()->zcount($key, $min, $max);
    }

    /**
     * 列出符合条件的key
     * @param $pattern
     * @return array
     */
    public function redisKeys($pattern)
    {
        return redis()->keys($pattern);
    }
}
